﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ThridGroup.ERP.DTO.TransferTransfersDto;
using ThridGroup.ERP.EntityFrameworkCore;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ThridGroup.ERP.WarehouseManagement
{
    /// <summary>
    /// 转移调拨服务实现    ---tsh
    /// </summary>
    public class TransferTransfersServices : ApplicationService, ITransferTransfersServices
    {
        private readonly IRepository<TransferTransfersModel, int> _repository;

        public TransferTransfersServices(IRepository<TransferTransfersModel, int> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 获取转移调拨列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public async Task<(List<TransferTransfersDto> data, int total)> GetListAsync(QueryTransferTransfersDto query)
        {
            var queryable = await _repository.GetQueryableAsync();

            // 构建查询条件
            if (!string.IsNullOrWhiteSpace(query.TransferCode))
            {
                queryable = queryable.Where(x => x.TransferCode.Contains(query.TransferCode));
            }

            if (!string.IsNullOrWhiteSpace(query.TransferName))
            {
                queryable = queryable.Where(x => x.TransferName.Contains(query.TransferName));
            }

            if (!string.IsNullOrWhiteSpace(query.TransferType))
            {
                queryable = queryable.Where(x => x.TransferType == query.TransferType);
            }

            if (!string.IsNullOrWhiteSpace(query.RemoveRepository))
            {
                queryable = queryable.Where(x => x.RemoveRepository.Contains(query.RemoveRepository));
            }

            if (!string.IsNullOrWhiteSpace(query.MoveWarehouse))
            {
                queryable = queryable.Where(x => x.MoveWarehouse.Contains(query.MoveWarehouse));
            }

            // 获取总数
            var total = await queryable.CountAsync();

            // 分页查询
            var data = await queryable
                .OrderByDescending(x => x.Id)
                .Skip((query.Page - 1) * query.Limit)
                .Take(query.Limit)
                .Select(x => new TransferTransfersDto
                {
                    Id = x.Id,
                    TransferCode = x.TransferCode,
                    TransferName = x.TransferName,
                    TransferType = x.TransferType,
                    RemoveRepository = x.RemoveRepository,
                    MoveWarehouse = x.MoveWarehouse,
                    TransferDate = x.TransferDate,
                    TransferState = x.TransferState,
                    Remark = x.Remark
                })
                .ToListAsync();

            return (data, total);
        }

        /// <summary>
        /// 根据ID获取转移调拨
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task<TransferTransfersDto> GetByIdAsync(int id)
        {
            var entity = await _repository.GetAsync(id);
            return new TransferTransfersDto
            {
                Id = entity.Id,
                TransferCode = entity.TransferCode,
                TransferName = entity.TransferName,
                TransferType = entity.TransferType,
                RemoveRepository = entity.RemoveRepository,
                MoveWarehouse = entity.MoveWarehouse,
                TransferDate = entity.TransferDate,
                TransferState = entity.TransferState,
                Remark = entity.Remark
            };
        }

        /// <summary>
        /// 创建转移调拨
        /// </summary>
        /// <param name="input">创建输入</param>
        /// <returns></returns>
        public async Task<TransferTransfersDto> CreateAsync(CreateTransferTransfersDto input)
        {
            var entity = new TransferTransfersModel
            {
                TransferCode = input.TransferCode,
                TransferName = input.TransferName,
                TransferType = input.TransferType,
                RemoveRepository = input.RemoveRepository,
                MoveWarehouse = input.MoveWarehouse,
                TransferDate = input.TransferDate,
                TransferState = 0, // 默认为草稿状态
                Remark = input.Remark
            };

            var result = await _repository.InsertAsync(entity, true);

            return new TransferTransfersDto
            {
                Id = result.Id,
                TransferCode = result.TransferCode,
                TransferName = result.TransferName,
                TransferType = result.TransferType,
                RemoveRepository = result.RemoveRepository,
                MoveWarehouse = result.MoveWarehouse,
                TransferDate = result.TransferDate,
                TransferState = result.TransferState,
                Remark = result.Remark
            };
        }

        /// <summary>
        /// 更新转移调拨
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="input">更新输入</param>
        /// <returns></returns>
        public async Task<TransferTransfersDto> UpdateAsync(int id, CreateTransferTransfersDto input)
        {
            var entity = await _repository.GetAsync(id);

            entity.TransferCode = input.TransferCode;
            entity.TransferName = input.TransferName;
            entity.TransferType = input.TransferType;
            entity.RemoveRepository = input.RemoveRepository;
            entity.MoveWarehouse = input.MoveWarehouse;
            entity.TransferDate = input.TransferDate;
            entity.Remark = input.Remark;

            var result = await _repository.UpdateAsync(entity, true);

            return new TransferTransfersDto
            {
                Id = result.Id,
                TransferCode = result.TransferCode,
                TransferName = result.TransferName,
                TransferType = result.TransferType,
                RemoveRepository = result.RemoveRepository,
                MoveWarehouse = result.MoveWarehouse,
                TransferDate = result.TransferDate,
                TransferState = result.TransferState,
                Remark = result.Remark
            };
        }

        /// <summary>
        /// 删除转移调拨
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task DeleteAsync(int id)
        {
            await _repository.DeleteAsync(id);
        }

        /// <summary>
        /// 生成转移单编号
        /// </summary>
        /// <returns></returns>
        public async Task<string> GenerateTransferCodeAsync()
        {
            var now = DateTime.Now;
            var code = $"TR{now:yyyyMMddHHmmss}";
            
            // 检查是否已存在相同编号
            var queryable = await _repository.GetQueryableAsync();
            var exists = await queryable.AnyAsync(x => x.TransferCode == code);
            
            if (exists)
            {
                // 如果存在，添加随机后缀
                var random = new Random();
                code += random.Next(10, 99).ToString();
            }

            return code;
        }
    }
}
